package com.zlp.netty.component;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author: zhulaiping
 * @time: 2022/8/29 13:37
 */
@Slf4j
public class NettyChannelClient2 {

    /**
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        //1.启动类
        ChannelFuture channelFuture = new Bootstrap()
                //添加EventLoop
                .group(group)
                //选择channel的实现，客户端使用socketChannel
                .channel(NioSocketChannel.class)
                //添加处理器
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    //连接后被调用
                    protected void initChannel(Channel channel) throws Exception {
                        channel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        channel.pipeline().addLast(new StringEncoder());
                    }
                })
                //异步非阻塞方法
                .connect(new InetSocketAddress("localhost", 8080));
        Channel channel = channelFuture.sync().channel();
        log.debug("channel:{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                if("q".equals(line)){
                    channel.close(); //异步非阻塞
                    //因为close方法是异步操作，放在此处也不行
                    //log.debug("任务结束后的善后操作");
                    break;
                }
                channel.writeAndFlush(line);
            }

        }).start();
        //后续操作放在此处，channel还为关闭，此已开始执行
        //log.debug("任务结束后的善后操作");

        //解决方式
        //1.同步方式处理关闭
        ChannelFuture closeFuture = channel.closeFuture();
        /*System.out.println("waiting close.....");
        closeFuture.sync();
        log.debug("任务结束后的善后操作");*/

        //2.异步方式处理关闭
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                log.debug("任务结束后的善后操作");
                group.shutdownGracefully();
            }
        });
    }
}
